using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameObjPool
{
    private static Dictionary<string, List<GameObject>> objs = new Dictionary<string, List<GameObject>>();

    public static GameObject GetGameObject(GameObject obj, bool fromPool = false)
    {
        if(!fromPool)
        {
            return GameObject.Instantiate(obj);
        }
        string sn = obj.name;
        if (!objs.ContainsKey(sn))
        {
            GameObject temp = GameObject.Instantiate(obj);
            List<GameObject> objList = new List<GameObject>();
            objList.Add(temp);
            objs.Add(sn, objList);
            return temp;
        }
        else
        {
            List<GameObject> objList;
            objs.TryGetValue(sn, out objList);
            for (int i=0; i<objList.Count; i++)
            {
                if(objList[i] == null)
                {
                    objList.RemoveAt(i);
                    continue;
                }
                if(!objList[i].activeSelf)
                {
                    objList[i].SetActive(true);
                    return objList[i];
                }
            }
            GameObject temp = Object.Instantiate(obj);
            objList.Add(temp);
            return temp;
        }
    }

    public static void Destroyobject(GameObject obj)
    {
        string objName = obj.name;
        objName = objName.Replace("(Clone)", "");
        if(objs.ContainsKey(objName))
        {
            obj.SetActive(false);
            obj.transform.SetParent(null);
        }
        else
        {
            GameObject.Destroy(obj);
        }
    }
}
